//
//  PhotoViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/5/13.
//

#import "PhotoViewController.h"
#import "AddFunyPicCollectionViewCell.h"
#import "AddModel.h"
@interface PhotoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end

@implementation PhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.zx_navTitle = SQNSLocalString(@"相册");
   
}

- (void)SQ_UIViewForSelfView{
    [self.collectionView registerClass:[AddFunyPicCollectionViewCell class] forCellWithReuseIdentifier:@"AddFunyPicCollectionViewCell"];
    [self.view addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.zx_navBar.mas_bottom);
    }];
//    [self SQ_collectViewAddRefresh];
    [self SQ_Header];
}
- (void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"1" forKey:@"current"];
    [dic setObject:@"9" forKey:@"size"];
    [HttpTool post:Url48 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        NSDictionary * data = [[NSDictionary alloc]initWithDictionary:httpModel.data];
        NSArray * moarray = [data objectForKey:@"records"];
        NSArray * array = [AddModel mj_objectArrayWithKeyValuesArray:moarray];
        [self.jsonArray removeAllObjects];
        [self.jsonArray addObjectsFromArray:array];
        AddModel * model = [AddModel new];
        model.isAdd = YES;
        [self.jsonArray addObject:model];
        [self.collectionView reloadData];
       
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}

-(void)SQ_ButtonClick:(AddModel*)model{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    [HttpTool SQ_Image:model.addImage successBlock:^(BaseModel * _Nonnull httpModel) {
            if ([httpModel.data isNotEmpty]) {
                [self SQ_uplode:httpModel.data];
            }else{
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"上传异常")];
                [self.jsonArray removeObject:model];
                [self.collectionView reloadData];
            }
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            
        }];
}
-(void)SQ_uplode:(NSString*)imageUrl{
     
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:imageUrl forKey:@"url"];
    [HttpTool post:Url49 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [self SQ_Header];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

 
#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.jsonArray.count<10) {
        return self.jsonArray.count;
    }
    return 9;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    AddFunyPicCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddFunyPicCollectionViewCell" forIndexPath:indexPath];
    AddModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    cell.model = model;
    cell.typeBtn.text = @"";
  return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    return CGSizeMake((SCREEN_WIDETH-40)/3.f-1, (SCREEN_WIDETH-40)/3.f-1);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 0, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    AddModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if (model.isAdd) {
        [self SQ_headerButtonClick];
    }else{
        [self SQ_deletedButtonClick:indexPath];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
-(void)SQ_deletedButtonClick:(NSIndexPath*)indexPath{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"操作") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"查看") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableArray * dataArray = [NSMutableArray new];
        [weakSelf.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            AddModel * model = (AddModel*)obj;
            if ([model.url isNotEmpty]) {
                YBIBImageData * data = [YBIBImageData new];
                data.imageURL = SQURLImage(model.url);
                data.projectiveView = [weakSelf.collectionView cellForItemAtIndexPath:indexPath];
                [dataArray addObject:data];
            }
        }];
        YBImageBrowser * brow = [YBImageBrowser new];
        brow.dataSourceArray = dataArray;
        brow.currentPage =  indexPath.item;
        [brow show];
        
   }];
     UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"删除") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        AddModel * model = [weakSelf.jsonArray objectAtIndex:indexPath.item];
        NSMutableDictionary * dic = [NSMutableDictionary new];
        [dic setObject:model.imageId forKey:@"ids"];
        [HttpTool post:Url50 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
            [weakSelf.jsonArray removeObjectAtIndex:indexPath.item];
            [weakSelf.collectionView reloadData];
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        }];
       
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}
 
-(void)SQ_headerButtonClick{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"选择照片") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_leftButtonClick];
    }];
    UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"相册") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_rightButtonClick];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}

-(void)SQ_leftButtonClick{
    WS(weakSelf);
    _imagePickerVc = [[UIImagePickerController alloc] init];
    _imagePickerVc.delegate = self;
    _imagePickerVc.allowsEditing = YES;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        weakSelf.imagePickerVc.sourceType = sourceType;
        [[Manager SQ_getCurrentViewController] presentViewController:weakSelf.imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    WS(weakSelf);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
        if (photo == nil)
            {
                photo = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
        [weakSelf SQ_caijian:photo];
    }else
    {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"相册数据异常")];
    }
}


-(void)SQ_rightButtonClick{
    WS(weakSelf);
    TZImagePickerController * vc = [[TZImagePickerController alloc]init];
    vc.maxImagesCount = 10-self.jsonArray.count;
    vc.allowPickingVideo = NO;
    vc.scaleAspectFillCrop = NO;
    [[Manager SQ_getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        for (UIImage * image in photos) {
            [weakSelf SQ_caijian:image];
        }
    }];
}

//添加图片到列表
-(void)SQ_caijian:(UIImage*)image {
    AddModel * model = [AddModel new];
    model.addImage = image;
    [self SQ_ButtonClick:model];
}
 



@end
